package com.chenyaowei.happyhub.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/*
实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    @ExcelIgnore  //不导出该属性到excel
    private int id;
    @ExcelProperty("名称")  //excel的头名称
    private String name;
    @ExcelProperty("性别")  //excel的头名称
    private String sex;
    @ExcelProperty("工作")  //excel的头名称
    private String work;
}
*/


/*

控制器

@GetMapping("/test")
@ResponseBody
public void test(HttpServletResponse response) throws IOException {

        List<User> UserList = new ArrayList<>();
        UserList.add(new User(1,"小明","男","医生"));
        ExcelUntil.writeExcel(response, UserList);

}
*/


/*
        依赖
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.7</version>
        </dependency>
 */


public class ExcelUntil {
    public static void writeExcel(HttpServletResponse response, List lists) throws IOException {
        if (lists.size() <= 0) return;
        String fileName = lists.get(0).getClass().getSimpleName();
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        response.addHeader("Content-Disposition", "filename=" + fileName + ".xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet sheet = EasyExcel.writerSheet(0, "sheet").head(lists.get(0).getClass()).build();
        excelWriter.write(lists, sheet);
        excelWriter.finish();
    }
}
